﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Batman.BLL.UserModule.Extensions;
using Batman.Core;
using Batman.DLL.Todo;
using Batman.DLL.Todo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Batman.Web.Api.Todo.Controllers
{

    [ApiController]
    [Route("todo/[controller]")]
    public class GroupController : ControllerBase
    {
        private TodoDbContext _todoDbContext;

        public GroupController(TodoDbContext todoDbContext)
        {
            this._todoDbContext = todoDbContext;
        }

        [HttpPost]
        public async Task<ResponseBase<TodoGroup>> Post(TodoGroup model)
        {
            if (string.IsNullOrEmpty(model.GroupName.Trim()))
                return new ResponseBase<TodoGroup>(false, "组名不能空");

            var userId = HttpContext.User.GetUserId();
            using (_todoDbContext)
            {
                model.OwnerId = userId;
                await _todoDbContext.AddAsync(model);
                await _todoDbContext.SaveChangesAsync();

                return new ResponseBase<TodoGroup>(model);
            }
        }

        [HttpDelete]
        public async Task<ResponseBase<TodoGroup>> Delete(int id)
        {
            using (_todoDbContext)
            {
                var group = _todoDbContext.TodoGroup.AsNoTracking().FirstOrDefault(t => t.Id == id);
                if (group == null) return new ResponseBase<TodoGroup>();

                _todoDbContext.Remove(group);
                await _todoDbContext.SaveChangesAsync();
                return new ResponseBase<TodoGroup>(group);
            }
        }

        [HttpPut]
        [Route("Name")]
        public async Task<ResponseBase<TodoGroup>> UpdateName(TodoGroup model)
        {
            using (_todoDbContext)
            {
                var group = _todoDbContext.TodoGroup.AsNoTracking().FirstOrDefault(t => t.Id == model.Id);
                if (group == null) return new ResponseBase<TodoGroup>();

                group.GroupName = model.GroupName;

                _todoDbContext.Update(group);
                await _todoDbContext.SaveChangesAsync();
                return new ResponseBase<TodoGroup>(group);
            }
        }


        [HttpPut]
        [Route("TOp")]
        public async Task<ResponseBase<TodoGroup>> UpdateTop(TodoGroup model)
        {
            using (_todoDbContext)
            {
                var group = _todoDbContext.TodoGroup.AsNoTracking().FirstOrDefault(t => t.Id == model.Id);
                if (group == null) return new ResponseBase<TodoGroup>();

                group.IsTop = model.IsTop;
                _todoDbContext.Update(group);
                group.TopAt = group.IsTop ? DateTime.Now : default(DateTime?);
                await _todoDbContext.SaveChangesAsync();
                return new ResponseBase<TodoGroup>(group);
            }
        }
    }
}
